<template>
  <div class="app-container">
    <!-- 当前课程信息显示区域 -->
    <el-card v-if="currentCourseInfo" class="mb-20" shadow="never">
      <div class="course-header">
        <el-row :gutter="20" align="middle">
          <el-col :span="18">
            <div class="course-title">
              <i class="el-icon-back" @click="goBack" style="cursor: pointer; margin-right: 10px; color: #409EFF;"></i>
              <span class="title-text">课程章节管理</span>
              <el-divider direction="vertical"></el-divider>
              <el-tag type="primary" size="medium">{{ currentCourseInfo.chapterName }}</el-tag>
            </div>
            <div class="course-subtitle">
              <span class="subtitle-text">当前查看：{{ currentCourseInfo.chapterName }} 的章节列表</span>
            </div>
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-button type="primary" icon="el-icon-back" size="small" @click="goBack">
              返回课程列表
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="课件名称" prop="coursewareName">
        <el-input
          v-model="queryParams.coursewareName"
          placeholder="请输入课件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="章节名称" prop="chapterName">
        <el-input
          v-model="queryParams.chapterName"
          placeholder="请输入章节名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="coursewareType">
        <el-input
          v-model="queryParams.coursewareType"
          placeholder="请输入文件类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="coursewareStatus">
        <el-select
          v-model="queryParams.coursewareStatus"
          placeholder="请选择状态"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option label="正常" :value="1"></el-option>
          <el-option label="删除" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['courseManagement:courseware:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['courseManagement:courseware:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['courseManagement:courseware:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['courseManagement:courseware:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="coursewareList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课件id" align="center" prop="coursewareId" />
      <el-table-column label="课件名称" align="center" prop="coursewareName" />
      <el-table-column label="章节名称" align="center" prop="chapterName" />
      <el-table-column label="文件类型" align="center" prop="coursewareType" />
      <el-table-column label="文件大小(KB)" align="center" prop="coursewareSize" />
      <el-table-column label="课件路径" align="center" prop="coursewarePath" />
      <el-table-column label="状态" align="center" prop="coursewareStatus">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.coursewareStatus == 1"
            >正常</el-tag
          >
          <el-tag type="danger" v-else>删除</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['courseManagement:courseware:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['courseManagement:courseware:edit']"
            >预览</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['courseManagement:courseware:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课件管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属章节" prop="chapterName">
          <el-select
            v-model="form.chapterId"
            clearable
            placeholder="请选择章节"
          >
            <el-option
              v-for="item in chapterList"
              :key="item.chapterId"
              :label="item.chapterName"
              :value="item.chapterId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课件名称" prop="coursewareName">
          <el-input
            v-model="form.coursewareName"
            placeholder="请输入课件名称"
          />
        </el-form-item>
        <el-form-item label="课件上传" prop="coursewarePath">
          <el-upload
            class="upload-demo"
            ref="upload"
            action=""
            :file-list="fileList"
            :http-request="uploadImg"
            :before-upload="beforeUpload"
            :on-error="handleUploadError"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.webp,.svg,.ico,.tiff,.tif,.pdf,.txt,.md,.json,.xml,.html,.htm,.css,.js,.java,.py,.c,.cpp,.h,.cs,.php,.rb,.go,.rs,.swift,.kt,.scala,.sql,.sh,.bat,.ps1,.yaml,.yml,.ini,.conf,.log"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传可以预览的文件格式，且不超过80MB
              <br>
              支持的格式：图片(JPG,PNG,GIF等)、PDF文档、视频(MP4,AVI等)、音频(MP3,WAV等)、文本文件(TXT,MD,代码文件等)
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件类型" prop="coursewareType">
          <el-input
            v-model="form.coursewareType"
            placeholder="请上传课件"
            disabled
          />
        </el-form-item>
        <el-form-item label="文件大小" prop="coursewareSize" >
          <el-input v-model="form.coursewareSize" placeholder="请上传课件" disabled/>
        </el-form-item>
        <el-form-item label="状态" prop="coursewareStatus">
          <el-radio-group v-model="form.coursewareStatus">
            <el-radio :label="0">删除</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog 
      :title="previewTitle" 
      :visible.sync="previewVisible" 
      width="80%" 
      append-to-body
      :before-close="handlePreviewClose"
      @keyup.esc="previewVisible = false"
    >
      <!-- 文件信息 -->
      <div class="file-info" style="margin-bottom: 15px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <span class="info-label">文件类型：</span>
            <el-tag size="small" :type="getFileTypeTagType(previewFileType)">{{ (previewFileType || '未知').toUpperCase() }}</el-tag>
          </el-col>
          <el-col :span="8">
            <span class="info-label">文件大小：</span>
            <span>{{ formatFileSize(previewFileSize) }}</span>
          </el-col>
          <el-col :span="8">
            <span class="info-label">支持预览：</span>
            <el-tag size="small" :type="isPreviewSupported() ? 'success' : 'warning'">
              {{ isPreviewSupported() ? '是' : '否' }}
            </el-tag>
          </el-col>
        </el-row>
      </div>
      
      <div class="preview-container">
        <!-- 加载状态 -->
        <div v-if="previewLoading" class="loading-container">
          <i class="el-icon-loading"></i>
          <p>正在加载文件...</p>
        </div>
        
        <!-- 图片预览 -->
        <div v-else-if="isImageFile" class="image-preview">
          <img :src="previewFileUrl" alt="图片预览" style="max-width: 100%; height: auto;" />
        </div>
        
        <!-- PDF预览 -->
        <div v-else-if="isPdfFile" class="pdf-preview">
          <iframe 
            :src="previewFileUrl" 
            width="100%" 
            height="600px" 
            frameborder="0"
          ></iframe>
        </div>
        
        <!-- 视频预览 -->
        <div v-else-if="isVideoFile" class="video-preview">
          <video 
            :src="previewFileUrl" 
            controls 
            style="width: 100%; max-height: 500px;"
          >
            您的浏览器不支持视频播放
          </video>
        </div>
        
        <!-- 音频预览 -->
        <div v-else-if="isAudioFile" class="audio-preview">
          <audio 
            :src="previewFileUrl" 
            controls 
            style="width: 100%;"
          >
            您的浏览器不支持音频播放
          </audio>
        </div>
        
        <!-- 文本文件预览 -->
        <div v-else-if="isTextFile" class="text-preview">
          <div v-if="textContent === '正在加载文件内容...'" class="loading-text">
            <i class="el-icon-loading"></i> 正在加载文件内容...
          </div>
          <div v-else class="text-content" v-html="textContent"></div>
        </div>
        
        <!-- 不支持的文件类型 -->
        <div v-else class="unsupported-file">
          <i class="el-icon-document file-type-icon"></i>
          <el-alert
            title="不支持的文件类型"
            :description="`当前文件类型 ${previewFileType || '未知'} 不支持在线预览，请下载后查看`"
            type="warning"
            show-icon
            :closable="false"
          >
            <template slot="default">
              <el-button type="primary" size="small" @click="downloadFile">
                下载文件
              </el-button>
            </template>
          </el-alert>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关 闭</el-button>
        <el-button type="primary" @click="downloadFile">下 载</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCourseware,
  getCourseware,
  delCourseware,
  addCourseware,
  updateCourseware,
} from "@/api/courseManagement/courseware";
import { listChapter } from "@/api/courseManagement/chapter";
import { uploadIdCard } from "@/api/artGood/artGood";
import axios from "axios";
import Cookies from "js-cookie";
import { isExternal } from "@/utils/validate";

export default {
  name: "Courseware",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课件管理表格数据
      coursewareList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      campusId:null,
      // 当前章节信息
      currentCourseInfo: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        coursewareName: null,
        campusId: null,
        chapterName: null,
        coursewareType: null,
        coursewareStatus: null,
      },
      // 表单参数
      form: {
        coursewareStatus:1,
        campusId:null,
      },
      // 表单校验
      rules: {},
      // 上传的文件列表
      fileList: [],
      chapterList: [],
      // 文件预览相关
      previewTitle: "",
      previewVisible: false,
      previewFileUrl: "",
      isImageFile: false,
      isPdfFile: false,
      isVideoFile: false,
      isAudioFile: false,
      isTextFile: false,
      textContent: "",
      previewFileType: "",
      previewFileSize: 0,
      previewLoading: false,
    };
  },
  created() {
    const user= JSON.parse(Cookies.get("user"))
    this.campusId = user.campusId
    this.form.campusId = this.campusId;
    this.queryParams.campusId = this.campusId;
    //接收从章节页面传递过来的参数
    this.receiveParams();
    this.getList();
    
  },
  methods: {
    // 接收传递的参数
    receiveParams() {
      this.reset();
      const chapterId = this.$route.query.chapterId;
      const chapterName = this.$route.query.chapterName;
      
      // 如果有传递课程ID，则设置到查询参数中
      if (chapterId) {
        this.queryParams.chapterId = chapterId;
        // 如果有课程名称，也设置到查询参数中
        if (chapterName) {
          this.queryParams.chapterName = chapterName;
        }
        
        // 设置当前课程信息
        this.currentCourseInfo = {
          chapterId: chapterId,
          chapterName: chapterName || '未知课程'
        };
        
        // 显示消息提醒
        this.$message({
          message: `已切换到章节：${chapterName} 的课件管理`,
          type: 'success',
          duration: 3000,
          showClose: true
        });
      }
    },
    // 返回章节列表
    goBack() {
      this.$router.push('/courseManagement/chapter');
    },
    /** 查询课件管理列表 */
    getList() {
      this.loading = true;
      
      listCourseware(this.queryParams).then((response) => {
        this.coursewareList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询课程章节列表 */
    getChapterList() {
      listChapter(this.queryParams).then((response) => {
        this.chapterList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList = [];
    },
    // 表单重置
    reset() {
      this.form = {
        coursewareId: null,
        coursewareName: null,
        chapterId: null,
        coursewareType: null,
        coursewareSize: null,
        coursewarePath: null,
        coursewareStatus: 1,
        campusId:this.campusId,
        createTime: null,
        updateTime: null,
        demo1: null,
        demo2: null,
        demo3: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.coursewareId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getChapterList();
      this.open = true;
      this.title = "添加课件管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getChapterList();
      const coursewareId = row.coursewareId || this.ids;
      getCourseware(coursewareId).then((response) => {
        this.form = response.data;
        this.fileList = [{ name: this.form.coursewareName, url: this.form.coursewarePath }];
        this.open = true;
        this.title = "修改课件管理";
      });
    },
     /** 查看课件按钮 */
    handleView(row){
      this.previewFile(row);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.coursewareId != null) {
            updateCourseware(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourseware(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
      this.fileList = [];
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const coursewareIds = row.coursewareId || this.ids;
      this.$modal
        .confirm('是否确认删除课件管理编号为"' + coursewareIds + '"的数据项？')
        .then(function () {
          return delCourseware(coursewareIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "courseManagement/courseware/export",
        {
          ...this.queryParams,
        },
        `courseware_${new Date().getTime()}.xlsx`
      );
    },
    // 上传文件
    uploadImg(item) {
      // 上传文件需要formdata类型
      const formdata = new FormData();
      formdata.append("file", item.file);
      uploadIdCard(formdata).then((res) => {
        const fileExtension = item.file.name.split('.').pop().toLowerCase();
        const fileTypeText = fileExtension === 'pdf' ? 'PDF文档' : 
                           this.isImage(fileExtension) ? '图片文件' :
                           this.isVideo(fileExtension) ? '视频文件' :
                           this.isAudio(fileExtension) ? '音频文件' :
                           this.isText(fileExtension) ? '文本文件' : '文件';
        
        this.$modal.msgSuccess(`${fileTypeText}上传成功！文件名：${item.file.name}，大小：${(item.file.size / 1024 / 1024).toFixed(2)}MB`);
        this.form.coursewarePath = res.data.file.url;
        this.form.coursewareSize = res.data.file.size;
        this.form.coursewareType = res.data.file.fileName.split('.').pop();
        this.fileList = [
          {
            name: item.file.name,
            url: res.data.file.url,
          },
        ];
      }).catch((error) => {
        console.error('文件上传失败:', error);
        this.$modal.msgError('文件上传失败，请重试');
      });
    },
    
    // 上传前验证文件
    beforeUpload(file) {
      // 检查文件大小 (80MB = 80 * 1024 * 1024 bytes)
      const maxSize = 80 * 1024 * 1024;
      if (file.size > maxSize) {
        this.$modal.msgError(`文件大小不能超过80MB，当前文件大小: ${(file.size / 1024 / 1024).toFixed(2)}MB`);
        return false;
      }
      
      // 获取文件扩展名
      const fileName = file.name;
      const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
      
      // 检查是否为可以预览的文件类型
      const previewableTypes = [
        // 图片
        'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico', 'tiff', 'tif',
        // PDF
        'pdf',
        // 视频
        'mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv', 'm4v', '3gp', 'ogv',
        // 音频
        'mp3', 'wav', 'ogg', 'aac', 'flac', 'wma', 'm4a', 'opus',
        // 文本
        'txt', 'md', 'json', 'xml', 'html', 'htm', 'css', 'js', 'java', 'py', 'c', 'cpp', 'h', 'cs', 'php', 'rb', 'go', 'rs', 'swift', 'kt', 'scala', 'sql', 'sh', 'bat', 'ps1', 'yaml', 'yml', 'ini', 'conf', 'log'
      ];
      
      if (!previewableTypes.includes(fileExtension)) {
        this.$modal.msgError(`不支持的文件格式: ${fileExtension}，只能上传可以预览的文件格式`);
        return false;
      }
      
      // 显示文件信息
      // console.log(`准备上传文件: ${fileName}, 大小: ${(file.size / 1024 / 1024).toFixed(2)}MB, 类型: ${fileExtension}`);
      
      // 如果是PDF文件，显示特殊提示
      if (fileExtension === 'pdf') {
        console.log('检测到PDF文件，支持在线预览');
      }
      
      return true;
    },
    
    // 上传错误处理
    handleUploadError(err, file, fileList) {
      console.error('文件上传失败:', err);
      this.$modal.msgError('文件上传失败，请重试');
    },
    
    // 文件预览相关方法
    previewFile(row) {
      if (!row.coursewarePath) {
        this.$modal.msgError("文件路径不存在");
        return;
      }
      
      this.previewLoading = true;
      
      try {
        this.previewTitle = `预览 - ${row.coursewareName}`;
        
        // 处理文件URL路径
        let fileUrl = row.coursewarePath;
        if (!isExternal(fileUrl) && !fileUrl.startsWith('http')) {
          // 如果是相对路径，添加baseURL
          fileUrl = process.env.VUE_APP_BASE_API + fileUrl;
        }
        this.previewFileUrl = fileUrl;
        this.previewFileType = row.coursewareType || '';
        this.previewFileSize = row.coursewareSize || 0;
        
        // 判断文件类型
        this.isImageFile = this.isImage(row.coursewareType);
        this.isPdfFile = this.isPdf(row.coursewareType);
        this.isVideoFile = this.isVideo(row.coursewareType);
        this.isAudioFile = this.isAudio(row.coursewareType);
        this.isTextFile = this.isText(row.coursewareType);
        
        this.previewVisible = true;
        
        // 如果是文本文件，需要读取内容
        if (this.isTextFile) {
          this.loadTextContent(fileUrl);
        } else {
          // 对于其他文件类型，加载完成后设置loading为false
          this.previewLoading = false;
        }
      } catch (error) {
        console.error('预览文件失败:', error);
        this.$modal.msgError("预览文件失败，请检查文件路径和类型");
        this.previewLoading = false;
      }
    },
    
    // 判断是否为图片文件
    isImage(fileType) {
      if (!fileType) return false;
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico', 'tiff', 'tif'];
      return imageTypes.includes(fileType.toLowerCase());
    },
    
    // 判断是否为PDF文件
    isPdf(fileType) {
      if (!fileType) return false;
      return fileType.toLowerCase() === 'pdf';
    },
    
    // 判断是否为视频文件
    isVideo(fileType) {
      if (!fileType) return false;
      const videoTypes = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv', 'm4v', '3gp', 'ogv'];
      return videoTypes.includes(fileType.toLowerCase());
    },
    
    // 判断是否为音频文件
    isAudio(fileType) {
      if (!fileType) return false;
      const audioTypes = ['mp3', 'wav', 'ogg', 'aac', 'flac', 'wma', 'm4a', 'opus'];
      return audioTypes.includes(fileType.toLowerCase());
    },
    
    // 判断是否为文本文件
    isText(fileType) {
      if (!fileType) return false;
      const textTypes = ['txt', 'md', 'json', 'xml', 'html', 'htm', 'css', 'js', 'java', 'py', 'c', 'cpp', 'h', 'cs', 'php', 'rb', 'go', 'rs', 'swift', 'kt', 'scala', 'sql', 'sh', 'bat', 'ps1', 'yaml', 'yml', 'ini', 'conf', 'log'];
      return textTypes.includes(fileType.toLowerCase());
    },
    
    // 加载文本文件内容
    loadTextContent(fileUrl) {
      this.textContent = "正在加载文件内容...";
      axios.get(fileUrl, {
        responseType: 'text',
        timeout: 10000, // 10秒超时
      }).then((response) => {
        // 限制显示的内容长度，避免过大的文件影响性能
        const content = response.data;
        if (content.length > 50000) {
          this.textContent = content.substring(0, 50000) + "\n\n... (文件内容过长，已截断显示前50000字符)";
        } else {
          this.textContent = content;
        }
        this.previewLoading = false;
      }).catch((error) => {
        console.error('加载文本文件失败:', error);
        this.textContent = `<p style="color: #f56c6c;">加载文件内容失败</p><p>错误信息: ${error.message}</p><p>请尝试下载文件后查看</p>`;
        this.previewLoading = false;
      });
    },
    
    // 关闭预览对话框
    handlePreviewClose() {
      this.previewTitle = "";
      this.previewVisible = false;
      this.previewFileUrl = "";
      this.isImageFile = false;
      this.isPdfFile = false;
      this.isVideoFile = false;
      this.isAudioFile = false;
      this.isTextFile = false;
      this.textContent = "";
      this.previewFileType = "";
      this.previewFileSize = 0;
      this.previewLoading = false;
    },
    
    // 下载文件
    downloadFile() {
      if (this.previewFileUrl) {
        try {
          // 创建一个临时的a标签来下载文件
          const link = document.createElement('a');
          link.href = this.previewFileUrl;
          link.download = this.previewTitle.replace('预览 - ', '');
          link.target = '_blank';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          this.$modal.msgSuccess("开始下载文件");
        } catch (error) {
          console.error('下载文件失败:', error);
          this.$modal.msgError("下载文件失败，请检查文件路径");
        }
      } else {
        this.$modal.msgError("文件路径不存在");
      }
    },
    // 获取文件类型标签类型
    getFileTypeTagType(fileType) {
      if (!fileType) {
        return 'info';
      }
      if (this.isImage(fileType)) {
        return 'success';
      } else if (this.isPdf(fileType)) {
        return 'info';
      } else if (this.isVideo(fileType)) {
        return 'warning';
      } else if (this.isAudio(fileType)) {
        return 'primary';
      } else if (this.isText(fileType)) {
        return 'success';
      } else {
        return 'danger';
      }
    },
    // 判断文件是否支持预览
    isPreviewSupported() {
      if (!this.previewFileType) {
        return false;
      }
      return this.isImage(this.previewFileType) || 
             this.isPdf(this.previewFileType) || 
             this.isVideo(this.previewFileType) || 
             this.isAudio(this.previewFileType) || 
             this.isText(this.previewFileType);
    },
    // 格式化文件大小
    formatFileSize(size) {
      if (!size || size === 0) {
        return '未知';
      }
      if (size < 1024) {
        return size + ' B';
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB';
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + ' MB';
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
      }
    },
  },
};
</script>

<style scoped>
.element.style{
  width: 100px;
}
.preview-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-preview {
  text-align: center;
}

.pdf-preview {
  width: 100%;
  height: 600px;
}

.video-preview {
  text-align: center;
}

.audio-preview {
  text-align: center;
  padding: 20px;
}

.text-preview {
  width: 100%;
  max-height: 500px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.text-content {
  font-family: 'Courier New', monospace;
  white-space: pre-wrap;
  line-height: 1.5;
  font-size: 14px;
  color: #333;
}

.unsupported-file {
  text-align: center;
  padding: 40px;
}

.preview-container img {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-container video {
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-container audio {
  width: 100%;
  max-width: 400px;
}

/* 文件类型图标样式 */
.file-type-icon {
  font-size: 48px;
  color: #909399;
  margin-bottom: 20px;
}

/* 加载状态样式 */
.loading-text {
  text-align: center;
  color: #909399;
  font-style: italic;
}

/* 错误状态样式 */
.error-text {
  color: #f56c6c;
  text-align: center;
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .preview-container {
    min-height: 300px;
  }
  
  .pdf-preview {
    height: 400px;
  }
  
  .text-preview {
    max-height: 300px;
  }
}

/* 文件信息样式 */
.file-info {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.info-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

/* 上传提示样式 */
.el-upload__tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
  margin-top: 8px;
}
.el-form-item__label{
  font-size:13px
}
.mb-20 {
  margin-bottom: 20px;
}

.course-header {
  padding: 10px 0;
}

.course-title {
  display: flex;
  align-items: center;
}

.title-text {
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}

.course-subtitle {
  margin-top: 5px;
}

.subtitle-text {
  color: #606266;
  font-weight: 500;
}
</style>

